<?php
/**
 * Created by IntelliJ IDEA.
 * User: xingshi
 * Date: 16/8/28
 * Time: 下午1:13
 */

namespace App\Http\Controllers;

use App\Http\Requests;
use Auth;
use Cache;
use Cookie;
use DB;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Input;
use Log;
use Mail;
use Redirect;
use Reponse;
use View;
use Crypt;
use App\Resume;
use App\Eduexp;
use App\Workexp;
use App\Invitation;
use Validator;
use App\Permission;

class invitationController extends Controller
{
    static $URL = '/';
    public function __construct()
    {
        //          $this->middleware('auth');
    }

    public function index(Request $request){
		if (!Auth::check()) return;
        if (!Permission::user_is_super()) return;

		$userid = Auth::user()->id;
        $taskids = DB::select("select distinct(taskid) from solves where type=0 and userid=".$userid);
        $taskidsStr = "";
        $ok = false;
        foreach($taskids as $k=>$v){
            if($ok) $taskidsStr .= ",";
            $taskidsStr .= $v->taskid;
            $ok = true;
        }

        $jobs = DB::select("select * from jobs where taskid in (".$taskidsStr.")");

        $updated_at_map = array();
        $title_mp = array();
        $techlead_mp = array();
        $company_mp = array();

        $data = array();
        foreach($jobs as $k=>$v){
            $taskid = $v->taskid;
            $techleadid = $v->techleadid;

            $da = array();
            if(!key_exists($taskid, $updated_at_map)){
                $updated_at_map[$taskid] = DB::select("select updated_at from solves where taskid =".$taskid)[0]->updated_at;
            }
            if(!key_exists($taskid, $title_mp)){
                $title_mp[$taskid] = DB::select("select title from tasks where id =".$taskid)[0]->title;
            }
            if(!key_exists($taskid, $techlead_mp)){
                $techlead_mp[$techleadid] = DB::select("select * from techleads where id =".$techleadid)[0];
            }
            $techlead = $techlead_mp[$techleadid];
            if(!key_exists($techleadid, $company_mp)){
                $company_mp[$techleadid] = DB::select("select * from companies where id =".$techlead->companyid)[0];
            }
            $company = $company_mp[$techleadid];

			$dd = DB::select("select accepted from invitations where userid=".$userid." and jobid=".$v->id." and isdelete=0");
            if(count($dd)>0){
                $da["accepted"] = $dd[0]->accepted;
            }
			else $da["accepted"] = 0;

            $da["updated_at"] = explode(" ", $updated_at_map[$taskid])[0];
            $da["title"] = $title_mp[$taskid];
            $da["realname"] = $techlead->realname;
            $da["userid"] = $techlead->userid;
            $da["department"] = $techlead->department;
            $da["title"] = $techlead->title;
            $da["company"] = $company->name;
            $da["slogan"] = $company->slogan;
            $da["job"] = $v->title;
            $da["salary"] = $v->salary;
            $da["jobid"] = $v->id;

			$data[] = $da;
        }

        $resumes = Resume::whereRaw("userid = ?", [$userid])->get();
        $eduexps = Eduexp::whereRaw("userid = ? and isdelete=0", [$userid])->get();
		$workexps = Workexp::whereRaw("userid = ? and isdelete=0", [$userid])->get();
		$flag = 0;
		if(count($resumes) && $resumes[0]->phone_number != NULL) $flag += 1;
		if(count($eduexps)) $flag += 1;
		if(count($workexps)) $flag += 1;

		$flag2 = false;
		$resume = NULL;
		if(count($resumes)>0 && $resumes[0]->attachment_path != "") {
			$resume = $resumes[0];
			$flag2 = true;
		}

        $data = self::arr_sort($data, "updated_at", "desc");

        return View::make("invitation.index")->with(compact("data"))->with(compact("flag"))->with(compact("flag2"))->with(compact("resume"));
    }

	public function save_invitation(Request $request){
		$input = $request->all();
		$userid = Auth::user()->id;
		$jobid = $input["jobid"];
		$acc_type = $input["acc_type"];
		$invit = Invitation::whereRaw("userid = ? and jobid = ? and isdelete=0", [$userid, $jobid])->get();
		if(count($invit)==0){
			$data = array();
			$data["userid"]	= $userid;
			$data["jobid"]	= $jobid;
			$data["accepted"] = 1;
			$data["acc_type"] = $acc_type;
			$data["isdelete"] = 0;
			Invitation::create($data);
		}
		else{
			$invit[0]->accepted = 1;				
			$invit[0]->acc_type = $acc_type;
			$invit[0]->save();
		}
		$res = array();
		$res["acc"] = true;
        return response()->json($res);
	}

    public function save_touch(Request $request){
        $input = $request->all();
        $userid = Auth::user()->id;
        $jobid = $input["jobid"];
        $invit = Invitation::whereRaw("userid = ? and jobid = ? and isdelete=0", [$userid, $jobid])->get();
        if(count($invit)==0){
            $data = array();
            $data["userid"]	= $userid;
            $data["jobid"]	= $jobid;
            $data["hastouch"]	= 1;
            $data["isdelete"] = 0;
            Invitation::create($data);
        }
        else{
            $invit[0]->hastouch = 1;
            $invit[0]->save();
        }
        $res = array();
        $res["acc"] = true;
        return response()->json($res);
    }

    public function save_attachment(Request $request){
        $data = self::upload($request);
		$path = $data["path"];
		if($path == false){
			$res = array();
			$res["acc"] = false;
			$res["data"] = "请上传pdf,html,doc格式的文件";
			return response()->json($res);
		}

		$name = $data["name"];
        $userid = Auth::user()->id;
        $resumes = Resume::whereRaw("userid = ?", [$userid])->get();
        $resume = NULL;
        foreach($resumes as $k=>$v){
            $resume = $v;
        }
        if(count($resume) == 0){
            $input['userid'] = $userid;
            $input['attachment_path'] = $path;
            $input['attachment_name'] = $name;
            Resume::create($input);
        }
        else {
            $resume->attachment_path = $path;
            $resume->attachment_name = $name;
            $resume->save();
        }

		$res = array();
		$res['suc'] = true;
		$res["path"] = $path;
		$res["name"] = $name;
        return response()->json($res);
    }

    private function upload($request)
    {
        $file = array('file' => Input::file('attachment'));
        $rules  = [
            "file" => "required|mimes:pdf,doc,md,html,docx|max:10240"
        ];

        // doing the validation, passing post data, rules and the messages
        $validator = Validator::make($file, $rules);
        if ($validator->fails()) {
			return array("path"=>false);
        }

        if ($request->file('attachment')->isValid()) {
            $destinationPath = self::getrootdir(); // upload path
            $extension = $request->file('attachment')->getClientOriginalExtension(); // getting image extension
            $fileName = time() . rand(11111, 99999) . '.' . $extension; // renameing image
            $request->file('attachment')->move($destinationPath, $fileName); // uploading file to given path
            $path = self::$URL . $destinationPath . '/' . $fileName;
            return array("path"=>$path, "name"=>$request->file('attachment')->getClientOriginalName());
        }
        else return "";
    }

    private function getrootdir()
    {
        $email = Auth::user()->email;
        $emailpath = substr(md5($email), 0, 10);
        $destinationPath = 'uploads/attachment_' . $emailpath; // upload path
        if (!is_dir($destinationPath)) mkdir($destinationPath);
        return $destinationPath;
    }

    //二维数组,按值排序
    function arr_sort($array,$key,$order="asc"){//asc是升序 desc是降序
        $arr_nums=$arr=array();
        foreach($array as $k=>$v){
            $arr_nums[$k]=$v[$key];
        }
        if($order=='asc'){
            asort($arr_nums);
        }else{
            arsort($arr_nums);
        }
        foreach($arr_nums as $k=>$v){
            $arr[$k]=$array[$k];
        }

        return $arr;
    }

}
